﻿using AutoMapper;
using bookmeetingroom.Data;
using bookmeetingroom.Data.Entities;
using bookmeetingroom.Helper;
using bookmeetingroom.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace bookmeetingroom.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme,Roles="Admin")]
    public class MeetingRoomController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ILogger<BuildingController> _logger;
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly IMapper _mapper;


        public MeetingRoomController(ApplicationDbContext dbContext, IWebHostEnvironment hostingEnv,
            ILogger<BuildingController> logger, IMapper mapper)
        {
            _dbContext = dbContext;
            _hostingEnv = hostingEnv;
            _logger = logger;
            _mapper = mapper;
        }

        [HttpGet]
        public ActionResult List()
        {
            Guid guid = 
            this.User.GetCompanyID();

            

            var meetingrooms = _dbContext.MeetingRooms.Include(n => n.Building)
                .Include(n => n.MeetingRoomFacilities).ThenInclude(n => n.Facility)
                .Where(n => guid==Guid.Empty|| n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArray();

            return Ok(new { message = "", data = meetingrooms });
            
        }
        [HttpPost]
        public async Task<ActionResult> CreateOrUpdate(MeetingRoomModel meetingRoomModel)
        {
            if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages());

            DateTime opendate;
            if (!DateTime.TryParseExact(meetingRoomModel.OpenTime, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out opendate))
            {
                return BadRequest("起始时间有错误");
            }
            DateTime closedate;
            if (!DateTime.TryParseExact(meetingRoomModel.CloseTime, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out closedate))
            {
                return BadRequest("结束时间有错误");
            }

            if (opendate >= closedate)
            {
                return BadRequest("起始时间不能大于结束时间");
            }
            if (meetingRoomModel.Id <= 0)
            {
                MeetingRoom meetingRoom = _mapper.Map<MeetingRoom>(meetingRoomModel);

                meetingRoom.CompanyId = this.User.GetCompanyID();

                List<MeetingRoomFacility> list = new List<MeetingRoomFacility>();

                foreach (var id in meetingRoomModel.Facilities)
                {
                    MeetingRoomFacility meetingRoomFacility = new MeetingRoomFacility
                    {
                        FacilityId = id,
                        MeetingRoomId = meetingRoom.Id
                    };

                    list.Add(meetingRoomFacility);
                }

                meetingRoom.MeetingRoomFacilities.AddRange(list);

                meetingRoom.MarkAdded();

                _dbContext.Add(meetingRoom);
            }
            else
            {
                var originalMeetingRoom=_dbContext.MeetingRooms.Include(n => n.MeetingRoomFacilities).Where(n=>n.Id==meetingRoomModel.Id).Single();
                
                MeetingRoom meetingRoom = _mapper.Map(meetingRoomModel,originalMeetingRoom);

                meetingRoom.CompanyId = this.User.GetCompanyID();

                List<MeetingRoomFacility> list = new List<MeetingRoomFacility>();

                foreach (var id in meetingRoomModel.Facilities)
                {
                    MeetingRoomFacility meetingRoomFacility = new MeetingRoomFacility
                    {
                        FacilityId = id,
                        MeetingRoomId = meetingRoom.Id
                    };

                    list.Add(meetingRoomFacility);
                }
                meetingRoom.MeetingRoomFacilities=list;


                meetingRoom.MarkModified();

                _dbContext.Update(meetingRoom);
            }
            await _dbContext.SaveChangesAsync();

            var guid = this.User.GetCompanyID();

            var meetingrooms = _dbContext.MeetingRooms.Include(n => n.Building).Include(n => n.MeetingRoomFacilities).ThenInclude(n => n.Facility).Where(n => n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArray();


            return Ok(new { message = "", data = meetingrooms });

        }
        [HttpGet("{id}")]
        public async Task<ActionResult> Detail(int id)
        {
            Guid guid = this.User.GetCompanyID();

            var meetingRoom = await _dbContext.MeetingRooms.Include(n => n.MeetingRoomFacilities).Where(n => n.CompanyId == guid && n.Id == id)
                .SingleOrDefaultAsync();

            var meetingRoomModel = _mapper.Map<MeetingRoomModel>(meetingRoom);

            meetingRoomModel.Facilities = meetingRoom.MeetingRoomFacilities.Select(n => n.FacilityId).ToArray();

            return Ok(new { message = "", data = meetingRoomModel });
        }
        [HttpPost("Remove/{id}")]
        public async Task<ActionResult> Remove(int? id)
        {
            if (!id.HasValue) return BadRequest("不能找到会议室");

            var meetingRoom = await _dbContext.MeetingRooms.Include(n => n.MeetingRoomFacilities).Where(n=>n.Id==id.Value).SingleOrDefaultAsync();

            if (meetingRoom != null)
            {
                _dbContext.MeetingRooms.Remove(meetingRoom);

                await _dbContext.SaveChangesAsync();
            }

            var guid = this.User.GetCompanyID();

            var meetingrooms = _dbContext.MeetingRooms.Include(n => n.Building).Include(n => n.MeetingRoomFacilities).ThenInclude(n => n.Facility).Where(n => n.CompanyId == guid).OrderByDescending(n => n.UpdatedTime).ToArray();


            return Ok(new { message = "删除成功", data = meetingrooms });


        }

        [HttpPost("Upload")]
        public async Task<ActionResult> Upload()
        {
            //try
            {
                var files = Request.Form.Files;

                if (!files.Any()) return BadRequest("文件为空");

                var file = files[0];

                if (file.Length == 0) return BadRequest("文件为空");

                string fileName = Path.GetFileNameWithoutExtension(file.FileName)
                    + "_" + Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);


                if (_hostingEnv.EnvironmentName != "Development")
                {
                    string pysicalFileName = _hostingEnv.WebRootPath + $@"/images/meetingroom/{fileName}";
                    using (FileStream fs = System.IO.File.Create(pysicalFileName))
                    {
                        await file.CopyToAsync(fs);

                        await fs.FlushAsync();

                    }
                }
                else
                {
                    string pysicalFileName = _hostingEnv.WebRootPath + $@"/images/meetingroom/{fileName}";
                    using (FileStream fs = System.IO.File.Create(pysicalFileName))
                    {
                        await file.CopyToAsync(fs);

                        await fs.FlushAsync();

                    }
                }



                return Ok(new { message = "", data = Request.Scheme + "://" + Request.Host.Value + "/images/meetingroom/" + fileName });

            }
            //catch (Exception ex)
            //{
            //    _logger.LogError("上传文件错误：" + ex.ToString());

            //    return Ok(new { message = ex.Message });
            //}
        }

        //[AllowAnonymous]
        //public async Task<ActionResult> Download(string filename)
        //{

        //}
    }
}
